package com.example.contestsystem.Service;

import com.example.contestsystem.Dao.*;
import com.example.contestsystem.Entity.Contest;
import com.example.contestsystem.Entity.FileEntity;
import com.example.contestsystem.Entity.SignUpContest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ContestService {
    final ContestRepository contestRepository;
    final ContestFileRepository contestFileRepository;
    final SignUpContestRepository signUpContestRepository;
    final JoinTeamRepository joinTeamRepository;
    final TeamRepository teamRepository;
    private final TeamService teamService;
    private static final String UPLOAD_DIR = "D:\\Reserved\\"; // 指定文件保存的目录

    public ContestService(ContestRepository contestRepository, ContestFileRepository contestFileRepository,
                          TeamService teamService, SignUpContestRepository signUpContestRepository,
                          JoinTeamRepository joinTeamRepository, TeamRepository teamRepository) {
        this.contestRepository = contestRepository;
        this.contestFileRepository = contestFileRepository;
        this.teamService = teamService;
        this.signUpContestRepository = signUpContestRepository;
        this.joinTeamRepository = joinTeamRepository;
        this.teamRepository = teamRepository;
    }

    public String createContest(Contest contest) {
        String contestId = "ctst" + contest.getTeacherAccount() + (new Date()).hashCode();
        contest.setContestId(contestId);
        if(contest.getTeamMemberLimit() == 0)
            contest.setTeamMemberLimit(1);
        this.contestRepository.save(contest);
        return contestId;
    }

    public Contest findByContestId(String contestId) {
        return this.contestRepository.findByContestId(contestId);
    }

    public List<FileEntity> findFilesByContestId(String contestId) {
        return this.contestFileRepository.findByContestId(contestId);
    }

//    @Scheduled(cron = "0 0 0 * * ?") // 假设每天凌晨执行一次
//    public void processInactiveTeams() {
//        List<Contest> contests = contestRepository.findByIsValid(0);
//        for (Contest contest : contests) {
//            LocalDateTime localDateTime = LocalDateTime.now();
//            if (contest.getEndTime().isAfter(localDateTime) && contest.getStartTime().isBefore(localDateTime)) {
//                contest.setIsValid(1);
//                this.teamService.markInvalidTeams(contest.getContestId(), contest.getTeamMemberMin());
//            }
//        }
//    }

    public boolean checkParticipated(String contestId, int stuAccount) {
        return this.signUpContestRepository.findByContestIdAndStuAccount(contestId, stuAccount) != null;
    }

    public List<Contest> findByTeacherAccount(int teacherAccount) {
        return this.contestRepository.findByTeacherAccount(teacherAccount);
    }

    public boolean deleteContest(String contestId, int teacherId) {
        Contest desContest = this.contestRepository.findByContestId(contestId);
        if (desContest.getTeacherAccount() == teacherId) {
            this.signUpContestRepository.deleteByContestId(contestId);
            this.joinTeamRepository.deleteByContestId(contestId);
            this.teamRepository.deleteByContestId(contestId);
            this.contestFileRepository.deleteByContestId(contestId);
            this.contestRepository.deleteByContestId(contestId);
            deleteSubFolder(contestId);
            return true;
        }
        return false;
    }

    public boolean upload(String fileName, String filePath, String contestId) {
        FileEntity fileEntity = new FileEntity();
        fileEntity.setFileName(fileName);
        fileEntity.setFilePath(filePath);
        fileEntity.setContestId(contestId);
        if (fileName != null) {
            fileEntity.setFileId(String.valueOf(fileName.hashCode()));
        }
        this.contestFileRepository.save(fileEntity);
        return this.contestFileRepository.findByContestIdAndFileId(fileEntity.getContestId(), fileEntity.getFileId()) != null;
    }

    public boolean uploadFile(MultipartFile file, String contestId) {
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 拼接文件保存路径
            String subFolder = UPLOAD_DIR + contestId;
            String filePath = UPLOAD_DIR + contestId + File.separator + fileName;

            if (upload(fileName, filePath, contestId)) {
                // 创建目标文件
                File dest = new File(filePath);
                File contestFolder = new File(subFolder);
                // 检查目录是否存在，如果不存在就创建
                if (!contestFolder.exists() && !contestFolder.mkdirs())
                    return false;
                // 将文件保存到指定路径
                file.transferTo(dest);
                return true;
            }
        } catch (IOException e) {
            return false;
        }
        return false;
    }

    public boolean deleteSubFolder(String contestId) {
        File file = new File(UPLOAD_DIR + contestId);
        if (!file.exists())
            return false;
        File[] files = file.listFiles();
        if (files != null) {
            for (File f : files) {
                if(!f.delete())
                    return false;
            }
        }
        return file.delete();
    }

    public boolean deleteFile(String contestId, String fileName){
        File file = new File(UPLOAD_DIR + contestId + "\\" + fileName);
        if(file.exists())
            return file.delete();
        return false;
    }

    public boolean isPublisher(String contestId, int teacherAccount){
        return this.contestRepository.findByContestIdAndTeacherAccount(contestId, teacherAccount) != null;
    }

    public Page<Contest> findByStuAccount(int stuAccount, int pageIndex, int pageSize){
        Pageable pageable = PageRequest.of(pageIndex, pageSize);
        List<SignUpContest> signUpContests = this.signUpContestRepository.findByStuAccount(stuAccount);
        List<Contest> contests = new ArrayList<>();
        for(SignUpContest signUpContest: signUpContests){
            contests.add(this.contestRepository.findByContestId(signUpContest.getContestId()));
        }
        return new PageImpl<>(contests, pageable, contests.size());
    }

    public Page<Contest> findByTeacherAccount(int teacherAccount, int pageIndex, int pageSize){
        Pageable pageable = PageRequest.of(pageIndex, pageSize);
        List<Contest> contests = this.contestRepository.findByTeacherAccount(teacherAccount);
        return new PageImpl<>(contests, pageable, contests.size());
    }

    public List<Contest> findAllValid(){
        return this.contestRepository.findByIsValid(0);
    }

    public Page<Contest> findAllByPageIndex(int pageIndex, int pageSize){
        //分页
        Pageable pageable = PageRequest.of(pageIndex, pageSize);
        //分页查询
        return this.contestRepository.findAll(pageable);
    }
}
